﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Common.Net
{
    public class UrlHelper
    {
        public static string Content(string contentPath, HttpContextBase httpContext)
        {
            return GenerateContentUrl(contentPath, httpContext);
        }

        public static string GenerateContentUrl(string contentPath, HttpContextBase httpContext)
        {
            if (string.IsNullOrEmpty(contentPath))
            {
                contentPath = "~";
            }
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            if (contentPath[0] == '~')
            {
                return GenerateClientUrl(httpContext, contentPath);
            }
            return contentPath;
        }


        public static string GenerateClientUrl(HttpContextBase httpContext, string contentPath)
        {
            string str;
            if (string.IsNullOrEmpty(contentPath))
            {
                return contentPath;
            }
            contentPath = StripQuery(contentPath, out str);
            return (GenerateClientUrlInternal(httpContext, contentPath) + str);
        }


        private static string StripQuery(string path, out string query)
        {
            int index = path.IndexOf('?');
            if (index >= 0)
            {
                query = path.Substring(index);
                return path.Substring(0, index);
            }
            query = null;
            return path;
        }

        private static string GenerateClientUrlInternal(HttpContextBase httpContext, string contentPath)
        {
            if (string.IsNullOrEmpty(contentPath))
            {
                return contentPath;
            }
            if (contentPath[0] == '~')
            {
                string str = VirtualPathUtility.ToAbsolute(contentPath, httpContext.Request.ApplicationPath);
                string str2 = httpContext.Response.ApplyAppPathModifier(str);
                return GenerateClientUrlInternal(httpContext, str2);
            }
            string relativePath = MakeRelative(httpContext.Request.Path, contentPath);
            return MakeAbsolute(httpContext.Request.RawUrl, relativePath);
        }

        public static string MakeRelative(string fromPath, string toPath)
        {
            string str = VirtualPathUtility.MakeRelative(fromPath, toPath);
            if (!string.IsNullOrEmpty(str) && (str[0] != '?'))
            {
                return str;
            }
            return ("./" + str);
        }

        public static string MakeAbsolute(string basePath, string relativePath)
        {
            string str;
            basePath = StripQuery(basePath, out str);
            return VirtualPathUtility.Combine(basePath, relativePath);
        }
    }
}
